﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Repetition.Domain;
using NHibernate;
using NHibernate.Criterion;
using NHibernate.Transform;

namespace Repetition.Persistence.NHibernate
{
    public class ProblemRepository : Repository<Problem>, IProblemRepository
    {
        public ProblemRepository()
            : base() { }

        public ProblemRepository(ISession session)
            : base(session) { }

        public ICollection<Problem> GetBySubject(string subject)
        {
            return Session.CreateCriteria(typeof(Problem)).CreateCriteria("Subjects")
                .Add(Expression.Eq("Name", subject))
                .List<Problem>();
        }

        public ICollection<Problem> GetBySubjects(ICollection<Subject> subjects)
        {
            ICriteria criteria = Session.CreateCriteria(typeof(Problem)).CreateCriteria("Subjects");
            
            // Add or condition on subject name:
            Disjunction disjunction = new Disjunction();

            foreach (var subject in subjects)
                disjunction.Add(Expression.Eq("Name", subject.Name));

            criteria.Add(disjunction);
            
            // Remove duplicates Problems from the result set:
            criteria.SetResultTransformer(new DistinctRootEntityResultTransformer());

            return criteria.List<Problem>();
        }
    }
}
